<?php


namespace app\sports\company\service;


use think\Exception;
use app\common\HTTP;
use app\common\Redis;
use think\facade\Log;
use app\sports\company\model\CompanyDataModel;
use app\common\InstanceTrait;

class CompanyDataCaiji
{
    private $user = '';
    private  $secret ='';
//    接口名:足球指数采集 -- 3秒/次
//    接口频次:3/s 无限制
    private $url = 'open.sportnanoapi.com/api/sports/football/odds/live_history';

    protected function __construct()
    {
        $this->user = Env::get('nami.user');
        $this->secret = Env::get('nami.secret');
    }
    /*
     * 采集百欧公司数据
     */
    public function Execs(){
        try{
            $companydataressult = json_decode(HTTP::getInstance()->doGet($this->url."?user=$this->user&secret=$this->secret"), true);
////      数据样子:
//            {
//    2: [//指数公司id,详见状态码->指数公司ID
//        [
//            2729666,//纳米比赛id
//            "bs",//指数类型:bs-大小球
//            [
//                1565783249,//变化时间
//                "89",//比赛进行时间，未开始为空
//                "6.0,4.5,0.11,0",//大球,盘口,小球,是否封盘：1-封盘,0-未封盘
//                4 //比赛状态,详见状态码->足球比赛状态
//            ],
//            "0-4"//实时比分,主队-客队
//        ],
//        [
//            2687730,
//            "asia", //指数类型:asia-亚盘
//            [
//                1565783239,
//                "",
//                "1.1,-0.5,0.7,0",//主胜,盘口,客胜,是否封盘：1-封盘,0-未封盘
//                1
//            ],
//            "0-0"
//        ],
//        [
//            2730308,
//            "eu",//指数类型:eu-欧赔
//            [
//                1565783236,
//                "44",
//                "4.75,3.0,1.833,0",//主胜,和局,客胜,是否封盘：1-封盘,0-未封盘
//                2
//            ],
//            "1-1"
//        ],
//    ];
//}
//        思路:
//            遍历第一层数据,第一层数组是每个百欧公司
//            第二层是每一个纳米比赛的相应的数据
//            组装好每一条数据
//            批量插入

//            第一层是每个公司
            $addall=[];
        foreach ($companydataressult as $key => $value){
//            第二层是每个公司的每场比赛的纳米id的数据
            foreach ($value as $k=> $v) {
                $addall[$k] = [
                    'company_id' => $key,
                    'nami_match_id' => $value[0],
                    'bs' => '',
                    'asia' => '',
                    'eu' => '',
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'update_time' => date('Y-m-d H:i:s', time()),
                ];

//              判断是都存在大小球
                if (isset($v['bs']) && (!empty($v['bs']))) {
                    $addall[$k] = [
                        'bs' => json_encode($v['bs'], JSON_UNESCAPED_UNICODE),
                    ];
                    $explode = explode(',', $v['bs'][2]);
                    for ($i = 0;$i <= 3;$i++) {
                        $arr = [0 => 'sheng', 1 => 'ping', 2 => 'fu'];
                        //存储最大值key
                        $max = "company:max:{$value[0]}:$key:{$v['bs']}:{$arr[$i]}";
                        $min = "company:min:{$value[0]}:$key:{$v['bs']}:{$arr[$i]}";
                        //读取redis最大值
                        $maxredis = Redis::getInstance()->redisGet($max);
                        //读取redis最小值
                        $minredis = Redis::getInstance()->redisGet($min);
//                       判断是否读取成功
                        if ($minredis['code'] != _MSG_NOT_FOUND) {
                            $minres = $minredis < $explode[$i] ? $minredis : $explode[$i];
                            if ($minres != $maxredis) {
                                //          存储一个月数据
                                Redis::getInstance()->redisSet($min, $minres, 86400 * 30);
                            }
                        }
//                       判断是否有读取到值
                        if ($maxredis['code'] != _MSG_NOT_FOUND) {
                            $maxres = $maxredis > $explode[$i] ? $maxredis : $explode[$i];
                            if ($maxres != $maxredis) {
                                //          存储一个月数据
                                Redis::getInstance()->redisSet($max, $maxres, 86400 * 30);
                            }
                        };
                    }

//                    存储大小球盘与实时盘的数据
                    $listkey = "company:{$value[0]}:$key";
                    $bs = json_encode($v['bs'],JSON_UNESCAPED_UNICODE);
                    Redis::getInstance()->redisLpush($listkey,$bs);
                }
//              判断亚盘是否有存在
                if (isset($v['asia']) && (!empty($v['asia']))) {
                    $addall[$k] = [
                        'asia' => json_encode($v['asia'], JSON_UNESCAPED_UNICODE),
                    ];
                    $explode = explode(',', $v['asia'][2]);
                    for ($i = 0;$i <= 3;$i++) {
                        $arr = [0 => 'sheng', 1 => 'ping', 2 => 'fu'];
                        //存储最大值key
                        $max = "company:max:{$value[0]}:$key:{$v['asia']}:{$arr[$i]}";
                        $min = "company:min:{$value[0]}:$key:{$v['asia']}:{$arr[$i]}";
                        //读取redis最大值
                        $maxredis = Redis::getInstance()->redisGet($max);
                        //读取redis最小值
                        $minredis = Redis::getInstance()->redisGet($min);
//                       判断是否读取成功
                        if ($minredis['code'] != _MSG_NOT_FOUND) {
                            $minres = $minredis < $explode[$i] ? $minredis : $explode[$i];
                            if ($minres != $maxredis) {
                                //          存储一个月数据
                                Redis::getInstance()->redisSet($min, $minres, 86400 * 30);
                            }
                        }
//                       判断是否有读取到值
                        if ($maxredis['code'] != _MSG_NOT_FOUND) {
                            $maxres = $maxredis > $explode[$i] ? $maxredis : $explode[$i];
                            if ($maxres != $maxredis) {
                                //          存储一个月数据
                                Redis::getInstance()->redisSet($max, $maxres, 86400 * 30);
                            }
                        };
                    }
                    //存储亚盘初始盘与实时盘的数据
                    $listkey = "company:list:{$value[0]}:$key:'asia'";
                    $bs = json_encode($v['asia'],JSON_UNESCAPED_UNICODE);
                    Redis::getInstance()->redisLpush($listkey,$bs);
                }
//              判断是否存在欧盘
                if (isset($v['eu']) && (!empty($v['eu']))) {
                    $addall[$k] = [
                        'eu' => json_encode($v['eu'], JSON_UNESCAPED_UNICODE),
                    ];
                    $explode = explode(',', $v['eu'][2]);
                    for ($i = 0;$i <= 3;$i++) {
                        $arr = [0 => 'sheng', 1 => 'ping', 2 => 'fu'];
                        //存储最大值key
                        $max = "max:{$value[0]}:$key:{$v['eu']}:{$arr[$i]}";
                        $min = "min:{$value[0]}:$key:{$v['eu']}:{$arr[$i]}";
                        //读取redis最大值
                        $maxredis = Redis::getInstance()->redisGet($max);
                        //读取redis最小值
                        $minredis = Redis::getInstance()->redisGet($min);
//                       判断是否读取成功
                        if ($minredis['code'] != _MSG_NOT_FOUND) {
                            $minres = $minredis < $explode[$i] ? $minredis : $explode[$i];
                            if ($minres != $maxredis) {
                                //          存储一个月数据
                                Redis::getInstance()->redisSet($min, $minres, 86400 * 30);
                            }
                        }
//                       判断是否有读取到值
                        if ($maxredis['code'] != _MSG_NOT_FOUND) {
                            $maxres = $maxredis > $explode[$i] ? $maxredis : $explode[$i];
                            if ($maxres != $maxredis) {
                                //          存储一个月数据
                                Redis::getInstance()->redisSet($max, $maxres, 86400 * 30);
                            }
                        }
                    }
                    //存储欧盘初始盘与实时盘的数据
                    $listkey = "company:{$value[0]}:$key";
                    $bs = json_encode($v['eu'],JSON_UNESCAPED_UNICODE);
                    Redis::getInstance()->redisLpush($listkey,$bs);
                }
             }
          }



//        处理公司列表
        $listcompany = Redis::getInstance()->redisLrange($key,0,-1);
//        遍历上面的数组
        foreach ($addall as $addlist){
            处理公司列表
        $listcompany = Redis::getInstance()->redisLrange($key,0,-1);
            if (!in_array($addlist['company_id'],$listcompany)){
//                组装好key
                $key = "company:{$addlist['nami_match_id']}:companyList";
//                添加到队列中
                Redis::getInstance()->redisLpush($key,$addlist['company_id']);
            }
        }

//        数据批量写入数据库
        CompanyDataModel::getInstance()->InsertCompanyDataAll($addall);
        }catch(Exception $e){
         $error = json_encode([
                'msg' => $e->getMessage(),
                'line' => $e->getLine(),
                'code' => $e->getCode(),
            ],JSON_UNESCAPED_UNICODE);
            Log::error('足球指数采集错误BifenCaijidata:'.$error);
            return [];
        }
    }
}